//
//  OMGMyViewController.m
//  A_project2.0
//
//  Created by Tiny on 16/3/7.
//  Copyright © 2016年 七平. All rights reserved.
//

#import "OMGMyViewController.h"
#import "QP_CleanCachesGroup.h"
#import "OMG_CollectionViewController.h"
@interface OMGMyViewController ()<UITableViewDataSource,UITableViewDelegate>
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic, strong) NSMutableArray *imgArr;
@end

@implementation OMGMyViewController
- (void)viewWillAppear:(BOOL)animated
{
    NSString *userImg = [[NSUserDefaults standardUserDefaults]objectForKey:@"userImg"];
    if (userImg) {
        // 将字符串转化Data
        NSData *img = [[NSData alloc]initWithBase64EncodedString:userImg options:NSDataBase64DecodingIgnoreUnknownCharacters];
        [self.userImageView setImage:[UIImage imageWithData:img]];
    }
//        self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"我的";
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    self.tableView.contentInset = UIEdgeInsetsMake(200, 0, 0, 0);
    [self dataHandler];                     /**< 数据处理 */
    UIImageView *img = [[UIImageView alloc]initWithFrame:CGRectMake(0, - 200, WIDTH_VIEW, 210)];
    img.image = [UIImage imageNamed:@"fengjing.jpg"];
    img.userInteractionEnabled = YES;
//    _tableView.tableHeaderView = img;
    [self.tableView addSubview:img];
    
    img.contentMode = UIViewContentModeScaleAspectFill;
    img.tag = 101;

    // 头像
    self.userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH_VIEW / 5, WIDTH_VIEW / 5)];
    _userImageView.center = CGPointMake(WIDTH_VIEW / 5 / 2 + 10, -20 - WIDTH_VIEW / 5 / 2+10);
    _userImageView.backgroundColor =[UIColor redColor];
    _userImageView.contentMode = UIViewContentModeScaleAspectFill;
    _userImageView.layer.cornerRadius = _userImageView.frame.size.width / 2;
    _userImageView.clipsToBounds = YES;
    _userImageView.userInteractionEnabled = YES;
    _userImageView.image = [UIImage imageNamed:@"touxiang.jpg"];
    [_tableView addSubview:_userImageView];
    
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeImgAction)];
    [self.userImageView addGestureRecognizer:tap];
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGPoint point = scrollView.contentOffset;
    if (point.y < -200 ) {
        CGRect rect = [self.tableView viewWithTag:101].frame;
        rect.origin.y = point.y;
        rect.size.height = -point.y;
        [self.tableView viewWithTag:101].frame = rect;
    }

}
- (void)dataHandler
{
    self.dataArr = [@[@"我的收藏", @"清除缓存",@"意见反馈",@"联系客服"]mutableCopy];
    self.imgArr = [@[@"shixin.png",@"huicun.png",@"fankui.png",@"kefu.png"]mutableCopy];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    cell.textLabel.text = _dataArr[indexPath.row];
    cell.imageView.image =[UIImage imageNamed:_imgArr[indexPath.row]];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {

        self.hidesBottomBarWhenPushed = YES;
        self.navigationController.navigationBarHidden = NO;

        OMG_CollectionViewController *p = [[OMG_CollectionViewController alloc]init];
        [self.navigationController pushViewController:p animated:YES];
    }else if (indexPath.row == 1){  /**< 清除缓存 */
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清理缓存" message:@"" preferredStyle:UIAlertControllerStyleAlert];
        // 获取缓存路径
        NSString *cashPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)objectAtIndex:0];
        // 计算文件夹大小
        CGFloat flieSize = [QP_CleanCachesGroup folderSizeAtPath:cashPath];
        // 计算图片的大小
        CGFloat imgSize = [[SDImageCache sharedImageCache] getSize];
        dispatch_async(dispatch_get_main_queue(), ^{
            CGFloat m = flieSize + imgSize / (1024.0 * 1024.0);
            alert.message = [NSString stringWithFormat:@"%.2fMB",m];
            [_tableView reloadData];
        });
        // 取消按钮
        UIAlertAction *cancell = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        // 确定按钮
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 文件夹清缓存
            [QP_CleanCachesGroup clean:cashPath];
            // SDImage 清缓存
            [[SDImageCache sharedImageCache] cleanDisk];
        }];
        [alert addAction:cancell];
        [alert addAction:sure];
        [self presentViewController:alert animated:YES completion:nil];
    }else if (indexPath.row == 2){
        UIAlertController *feedback = [UIAlertController alertControllerWithTitle:@"意见反馈" message:@"发短信" preferredStyle:UIAlertControllerStyleAlert];
        // 取消按钮
        UIAlertAction *cancell = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        // 发短信
        UIAlertAction *msg = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:@"sms://10086"];
            [[UIApplication sharedApplication] openURL:url];
        }];
        [feedback addAction:cancell];
        [feedback addAction:msg];
        // 弹窗出现
        [self presentViewController:feedback animated:YES completion:nil];
    }else if (indexPath.row == 3){
        UIAlertController *feedback = [UIAlertController alertControllerWithTitle:@"联系客服" message:@"打电话" preferredStyle:UIAlertControllerStyleAlert];
        // 取消按钮
        UIAlertAction *cancell = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        // 打电话按钮
        UIAlertAction *tele = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:@"tel://10086"];
            [[UIApplication sharedApplication] openURL:url];
        }];
        [feedback addAction:cancell];
        [feedback addAction:tele];
        // 弹窗出现
        [self presentViewController:feedback animated:YES completion:nil];
    }
}

// 换头像
- (void)changeImgAction
{
    UIActionSheet *actionSheet = [[UIActionSheet alloc]initWithTitle:@"" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"拍照" otherButtonTitles:@"从相册中选择", nil];
    [actionSheet showInView:self.view];
}
// UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == actionSheet.cancelButtonIndex) {
        return;
    }else if (buttonIndex == actionSheet.destructiveButtonIndex){
        [self camera];
    }else{
        [self library];
    }
}
- (void)library
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeSavedPhotosAlbum]) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.mediaTypes = [NSArray arrayWithObjects:(NSString *)kUTTypeImage, nil];
        imagePicker.allowsEditing = NO;
        [self presentViewController:imagePicker animated:YES completion:^{
            
        }];
    }
}
- (void)camera
{
    // 判断是否可以打开相机 ,模拟器功能无法使用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES; // 是否可编辑
        // 摄像头
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:^{
            
        }];

    }else{
        // 如果没有
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"您没有摄像头" preferredStyle:UIAlertControllerStyleAlert];
        [self performSelector:@selector(diss) withObject:self afterDelay:2];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
- (void)diss
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
// 图片选中后
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        [self presentedViewController:image];
    }
}
- (void)presentedViewController:(UIImage *)image
{
    self.hidesBottomBarWhenPushed = YES;
    UIImage *newimage = [FilterVC effectImage:image byFilterName:@"None"];
    FilterVC *viewController = [[FilterVC alloc]init];
    
    //    void (^changeImgBlock) (NSString*) = ^(NSString* image){
    //        //将字符串转化Data
    //                    NSData *userImg = [[NSData alloc] initWithBase64EncodedString:image options:NSDataBase64DecodingIgnoreUnknownCharacters];
    //        [self.userImageView setImage:[UIImage imageWithData:userImg]];
    //    };
    //    viewController.changeImgBlock = changeImgBlock;
    
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:viewController];
    [viewController setOriginalImage:image];
    [viewController setImage:newimage];
    
    [self.navigationController pushViewController:viewController animated:YES];
    self.hidesBottomBarWhenPushed = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
